#include "RelOp.h"

void SelectFile::Run (DBFile &inFile, Pipe &outPipe, CNF &selOp, Record &literal) {
	    util=new Util{&inFile, &outPipe, &selOp, &literal};
		pthread_create(&thread, NULL, workerFunction, util);
	}

void *workerFunction(void* arg){

		Util *util = (Util *) arg;
		buffer = new Record;

			ComparisonEngine ceng;
			DBFile *dbfile = util->inFile;
			dbfile->MoveFirst ();
			int counter=0,inserted=0;
			while (dbfile->GetNext (*buffer) == 1) {
				counter ++;
				if (counter%100000 == 0) {
					 cerr <<"."<< endl;
				}
				if (ceng.Compare (buffer, util->literal,util->selOp)){								//if the CNF is matching with the record
							util->outPipe->Insert(buffer);
							inserted++;
				}
			}
			delete buffer;
			delete util;
			cerr << "Scanned "<<counter<<" records. Inserted " << inserted << " recs into the pipe\n";
	}


/*void *SelectFile::workerFunction(void *arg){

	Util *util = (Util *) arg;
	buffer = new Record;

		ComparisonEngine ceng;
		DBFile *dbfile = util->inFile;
		dbfile->MoveFirst ();
		int counter=0,inserted=0;
		while (dbfile->GetNext (*buffer) == 1) {
			counter ++;
			if (counter%100000 == 0) {
				 cerr <<"."<< endl;
			}
			if (ceng.Compare (buffer, util->literal,util->selOp)){								//if the CNF is matching with the record
						util->outPipe->Insert(buffer);
						inserted++;
			}
		}
		delete buffer;
		delete util;
		cerr << "Scanned "<<counter<<" records. Inserted " << inserted << " recs into the pipe\n";
}*/


void SelectFile::WaitUntilDone () {
	 pthread_join (thread, NULL);
}

void SelectFile::Use_n_Pages (int runlen) {

}


void SelectPipe::Run (Pipe &inPipe, Pipe &outPipe, CNF &selOp, Record &literal) {

	util=new Util{&inPipe, &outPipe, &selOp, &literal};
	pthread_create(&thread, NULL, workerFunction, util);

}


void SelectPipe::workerFunction (void *arg){

	Util *util = (Util *) arg;
	int counter=0,inserted=0;
	buffer=new Record;
	ComparisonEngine ceng;
	while(util->inPipe->Remove(buffer)){
		counter ++;
					if (counter%100000 == 0) {
						 cerr <<"."<< endl;
					}
					if (ceng.Compare (buffer, util->literal,util->selOp)){								//if the CNF is matching with the record
								util->outPipe->Insert(buffer);
								inserted++;
					}
	}

	delete buffer;
	delete util;
	cerr << "Scanned "<<counter<<" records. Inserted " << inserted << " recs into the pipe\n";
}


void SelectPipe::WaitUntilDone () {
	 pthread_join (thread, NULL);
}

void SelectPipe::Use_n_Pages (int runlen) {

}
